<template>
  <div class="home">
    <van-search
      v-model="value"
      placeholder="请输入搜索关键词"
      show-action
      shape="round"
      @input="kwshow"
      @search="search"
    >
      <template #action>
        <span @click="search">搜索</span>
      </template>
    </van-search>

    <div>
      <!-- 搜索历史 -->
      <div v-show="show">
        <div class="search_box_top">
          <span>最近搜索</span>
          <van-icon name="delete" @click="del" />
        </div>
        <div class="search_box_list">
          <van-tag
            size="medium"
            v-for="(item,index) in kewSave"
            :key="index"
            style="margin: 2px;"
          >{{item}}</van-tag>
        </div>
      </div>
      <!-- 搜索关键词 -->
      <div class="seared_item_box" v-show="!show">
        <div v-for="(item,index) in kewshow" :key="index" v-html="item"></div>
      </div>
    </div>
  </div>
</template>

<script>
export default {
  data() {
    return {
      value: "",
      show: true
    };
  },
  // 自定义指令
  directives: {
    // 自定义指令名
    focus: {
      // 指令绑定时候要调用
      bind() {},
      inserted(el) {
        el.focus();
      }
    }
  },
  computed: {
    kewshow() {
      var temp = [];
      this.$store.state.kewshow.forEach(element => {
        if (element.includes(this.value)) {
          element = element.replace(
            this.value,
            `<span style="color:red">${this.value}</span>`
          );
          temp.push(element);
          // console.log(element);
        }
      });
      return temp;
    },
    kewSave() {
      return this.$store.state.kewSave;
    }
  },
  methods: {
    //最近搜索删除
    del() {
      this.$dialog.confirm({
        title: "全部删除历史记录？",
      })
        .then(() => {
        this.$store.state.kewSave=[]
        })
        .catch(() => {
          // on cancel
        });
    },
    // 触发input 显示关键字
    kwshow() {
      this.show = this.value.length === 0;
      this.$store.dispatch("KWSHOW", this.value);
    },
    // 点击搜索
    search() {
      // console.log('....');
      this.$store.dispatch("KEWSAVE", this.value);
    }
  }
};
</script>
<style scoped>
.search_box_top {
  display: flex;
  justify-content: space-between;
  text-align: center;
  align-items: center;
  padding: 8px;
  /* width: 100%; */
  height: 30px;
  border-top: 1px solid #eeee;
}
.search_box_list {
  display: flex;
  flex-wrap: wrap;
  text-align: center;
  align-items: center;
  justify-content: flex-start;
}
.seared_item_box > div {
  width: 100%;
  height: 34px;
  line-height: 34px;
  text-indent: 2rem;
  border-bottom: 1px solid red;
}
</style>
